import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;

public abstract class AbsServer extends Thread {

    private int port;

    public AbsServer(int port){
        this.port = port;
    }

    @Override
    public void run(){
        try {
            var server = new ServerSocket(port);

            System.out.println("服务器已启动");

            while(!isInterrupted()){
                System.out.println("正在等待客户端连接...");

                var client = server.accept();

                System.out.println(client.getRemoteSocketAddress().toString() + "连接到客户端");
                
                service(client);
            }

        } catch (Exception e) {
            //TODO:: 写入日志
            
        }
    }

    public abstract void service(Socket client);

    public void exit(){

        if(isInterrupted())
            return;

        try {
            interrupt();
            var socket = new Socket("127.0.0.1", port);
            
            //TODO:: 这里我还没想好要不要传点东西

            socket.close();
            wait();
        } catch (Exception e) {
            
        }
    }
}
